const ProfileService = require("../services/ProfileService");
const VALID_FIELDS = ["type", "describe", "income", "expend", "cash", "remark"];

const ProfileController = {
  // 添加
  add: async (req, res) => {
    const { body } = req;
    const profileFields = {};
    try {
      // 只更新有效的字段
      VALID_FIELDS.forEach((field) => {
        if (body[field]) {
          profileFields[field] = body[field];
        }
      });

      await ProfileService.add(profileFields);
      res.apiResponse({ message: "添加成功" });
    } catch (error) {
      res.apiResponse(new Error("服务器异常"));
    }
  },
  // 获取列表
  getList: async (req, res) => {
    let result = await ProfileService.getList();
    res.apiResponse({ message: "success", list: result });
  },
  // 查找单个
  getByid: async (req, res) => {
    let { id } = req.params;
    let result = await ProfileService.findId(id);
    res.apiResponse({ message: "success", list: result });
  },
  upadte: async (req, res) => {
    const { body } = req;
    let { id } = req.params;
    const profileFields = {};
    try {
      // 只更新有效的字段
      VALID_FIELDS.forEach((field) => {
        if (body[field]) {
          profileFields[field] = body[field];
        }
      });

      await ProfileService.upadte(id, profileFields);
      res.apiResponse({ message: "编辑成功" });
    } catch (error) {
      res.apiResponse(new Error("服务器异常"));
    }
  },
  //删除
  delete: async (req, res) => {
    let { id } = req.params;
    await ProfileService.delete(id);
    res.apiResponse({ message: "删除成功" });
  },
};

module.exports = ProfileController;
